<template>
  <div class="main-box">
    <div class="table-box">
      <ProTable ref="proTableRef" :columns="columns" :request-api="positionApi.page" :data-callback="dataCallback">
        <template #tableHeader>
          <el-button size="default" type="success" class="ml10" :icon="CirclePlus" @click="onOpenEdit({})">
            {{ $t("message.commonBtn.add") }}
          </el-button>
        </template>
        <template #operation="scope">
          <el-button size="small" text type="primary" @click="onOpenEdit(scope.row)">
            <el-icon><Edit /></el-icon>
            {{ $t("message.commonBtn.edit") }}
          </el-button>
          <el-button
            :disabled="scope.row.systemMark === 'SYSTEM'"
            size="small"
            text
            type="danger"
            @click="onRowDel(scope.row)"
            v-auth="'system:role:delete'"
          >
            <el-icon><Delete /></el-icon>
            {{ $t("message.commonBtn.delete") }}
          </el-button>
        </template>
      </ProTable>
    </div>
    <PositionDialog ref="positionDialogRef" @refresh="getTableData()" />
  </div>
</template>
<script setup lang="tsx" name="SystemPosition">
import { defineAsyncComponent, reactive, ref, watchEffect } from "vue";
import { ElMessageBox } from "element-plus";
import { feature } from "@/utils/axios-utils";
import { DictData, SysPosition } from "@/api-services/models/system";
import positionApi from "@/api-services/apis/system/positionApi";
import dictDataApi from "@/api-services/apis/system/dictDataApi";
import { ColumnProps, EnumProps, ProTableInstance } from "@/components/ProTable/interface";
import ProTable from "@/components/ProTable/index.vue";
import { SqlSugarPagedList, UnifyResult } from "@/api-services/unifyResult";
import { CirclePlus, Delete, Edit } from "@element-plus/icons-vue";
import { useI18n } from "vue-i18n";
import { NotificationError, NotificationSuccess } from "@/utils/notification";
import { PositionProps } from "./component/editPosition.vue";
const PositionDialog = defineAsyncComponent(() => import("./component/editPosition.vue"));
const positionDialogRef = ref<InstanceType<typeof PositionDialog> | null>(null);
const { t } = useI18n();
const proTableRef = ref<ProTableInstance>();
const state = reactive({
  loading: false,
  dictData: [] as Array<DictData.SysDictData> //字典数据
});
const positionType = ref<Array<EnumProps>>([]);
const dataCallback = (queryRes: UnifyResult<SqlSugarPagedList<SysPosition.SysPosition>>) => {
  let data = queryRes.data;
  return {
    items: data.items,
    totalCount: data.totalCount,
    pageIndex: data.pageIndex,
    pageSize: data.pageSize
  };
};
const columns: ColumnProps<SysPosition.SysPosition>[] = [
  {
    prop: "name",
    label: t("message.posInfo.posName"),
    search: { el: "input", key: "name" }
  },
  { prop: "remark", label: t("message.posInfo.remark") },
  {
    prop: "category",
    label: t("message.posInfo.posType"),
    enum: positionType.value,
    search: { el: "select", key: "category" },
    render: scope => {
      let data = state.dictData.filter(item => item.value == scope.row.category)[0];
      return (
        <el-tag size={data?.tagSize} type={data?.tagType}>
          {data?.name}
        </el-tag>
      );
    }
  },
  { prop: "sortCode", label: t("message.posInfo.sort") },
  { prop: "operation", label: t("message.commonBtn.oper"), fixed: "right" }
];

const getTableData = async () => {
  proTableRef.value?.getTableList();
};

// 打开修改角色弹窗
const onOpenEdit = (row: SysPosition.SysPosition) => {
  let title = t("message.userOperation.addPos");
  if (row.id) {
    title = t("message.userOperation.editPos");
  }
  const param: PositionProps = {
    title: title,
    positionData: row,
    positionType: state.dictData
  };
  positionDialogRef.value?.openDialog(param);
};

const onRowDel = (row: SysPosition.SysPosition) => {
  ElMessageBox.confirm(`${t("message.roleAlter.isDeleteRole")}：“${row.name}”`, t("message.commonBtn.alter"), {
    confirmButtonText: t("message.userAlter.confirm"),
    cancelButtonText: t("message.userAlter.cancel"),
    type: "warning"
  })
    .then(async () => {
      const [err] = await feature(positionApi.delete([{ id: row.id }]));
      if (err) {
        NotificationError(err.message);
      } else {
        NotificationSuccess(t("message.roleAlter.deleteRoleSuccess"));
        getTableData();
      }
    })
    .catch();
};

const queryPositionType = async () => {
  let [err, res] = await feature(dictDataApi.getDatalistByType("PosType"));
  if (err) {
    NotificationError(err.message);
  } else {
    state.dictData = res?.data.data ?? [];

    res?.data.data.forEach((item: DictData.SysDictData) => {
      let cur = {} as EnumProps;
      cur.label = item.name;
      cur.value = item.value;
      positionType.value.push(cur);
    });
  }
};

watchEffect(async () => {
  await queryPositionType();
});
</script>
